<template>
	<coreshop-page title="签到" mode="left">
		<view class="layout-checkIn-box">
			<view class="checkin-day">
				<view class="day-box">
					<view class="tit">{{ state.sumCount }}天</view>
					<view class="desc">已坚持打卡</view>
				</view>
				<view class="day-box">
					<view class="tit">{{ state.dataSource.length }}天</view>
					<view class="desc">本月累积打卡</view>
				</view>
			</view>

			<view class="content-box">
				<view class="bar">
					<!-- 显示年月 -->
					<view class="date">{{ state.cur_year || "--" }} 年 {{ state.cur_month || "--" }} 月</view>
					<view class="mounth-box">
						<!-- 上一个月 -->
						<view class="previous" @click="handleCalendar(0)">
							<button class="barbtn">上一月</button>
						</view>
						<!-- 下一个月 -->
						<view class="next" @click="handleCalendar(1)">
							<button class="barbtn">下一月</button>
						</view>
					</view>
				</view>
				<!-- 显示星期 -->
				<view class="week">
					<view v-for="(item, index) in state.weeks_ch" :key="index">{{ item }}</view>
				</view>
				<view class="myDateTable">
					<view v-for="(item, j) in state.days" :key="j" class='dateCell'>
						<view v-if="item.date">
							<!-- 已签到日期 -->
							<view v-if="item.isSign == true" class='cell greenColor '>
								<text>{{ item.date }}</text>
							</view>
							<!-- 漏签 -->
							<view @click="clickSignUp(item.date, 0)" class="cell bgGary"
								v-else-if="state.cur_year < state.toYear || (state.cur_year == state.toYear && state.cur_month < state.toMonth) || (state.cur_year == state.toYear && state.cur_month == state.toMonth && item.date < state.today)">
								<!-- 小程序不兼容这个 v-else-if="(new Date(cur_year+'-'+cur_month+'-'+item.date))<(new Date())"> -->
								<text>{{ item.date }}</text>
							</view>
							<!-- 今日未签到-->
							<view @click="clickSignUp(item.date, 1)" class="cell coreshop-text-white bgBlue"
								v-else-if="item.date == state.today && state.cur_month == state.toMonth && state.cur_year == state.toYear">
								<text>签到</text>
							</view>
							<!-- 当前日期之后 -->
							<view class="cell coreshop-text-white" v-else>
								<text>{{ item.date }}</text>
							</view>
						</view>

					</view>
				</view>

			</view>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { queryUserCheckByMonth, queryUserCheckCount, queryUserCheckIn } from '@/core/api';
	import { handleShowToast } from '@/core/utils';
	import type { Response } from '@/core/models';
	import { useShopConfigStore } from '@/core/store';
	import { ShowcheckInEnum } from '@/core/enum';

	/** 获取项目配置 */
	const shopConfigStore = useShopConfigStore();

	const state = reactive<{
		days : Array<any>;
		SignUp : Array<any>;
		cur_year : number;
		cur_month : number;
		today : number;
		toMonth : number;
		toYear : number;
		weeks_ch : Array<string>;
		dataSource : Array<any>;
		sumCount : number;
	}>({
		days: [],
		SignUp: [],
		cur_year: new Date().getFullYear(),
		cur_month: new Date().getMonth() + 1,
		today: new Date().getDate(), //本日
		toMonth: new Date().getMonth() + 1, //本月
		toYear: new Date().getFullYear(), //本年
		weeks_ch: ['日', '一', '二', '三', '四', '五', '六'],
		dataSource: [], //已签到的数据源 
		sumCount: 0,
	});

	onLoad(() => {
		if (shopConfigStore?.config?.checkInIsOpen == ShowcheckInEnum.no) {
			handleShowToast('签到功能未开启', 'error', () => {
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 15000)
			})
		} else {
			getUserCheckByMonth(state.cur_year, state.cur_month);
			getUserCheckCount();
		}

		calculateEmptyGrids(state.cur_year, state.cur_month);
		calculateDays(state.cur_year, state.cur_month);
		onJudgeSign();
	})

	/** 获取用户按月签到数据 */
	const getUserCheckByMonth = async (cur_year : number, cur_month : number) => {
		const checkByMonth : Response<any> = await queryUserCheckByMonth({
			year: cur_year,
			month: cur_month,
		})
		if (checkByMonth.status) {
			state.dataSource = checkByMonth?.data;
		} else {
			handleShowToast(checkByMonth.msg)
		}
	}

	/** 获取用户总签到次数 */
	const getUserCheckCount = async () => {
		const checkCount : Response<number> = await queryUserCheckCount();
		if (checkCount.status) {
			state.sumCount = checkCount?.data;
		} else {
			handleShowToast(checkCount.msg)

		}
	}

	/** 获取当月共多少天 */
	const getThisMonthDays = (year : number, month : number) => {
		return new Date(year, month, 0).getDate()
	}
	/** 获取当月第一天星期几 */
	const getFirstDayOfWeek = (year : number, month : number) => {
		return new Date(Date.UTC(year, month - 1, 1)).getDay();
	}

	/** 计算当月1号前空了几个格子，把它填充在days数组的前面 */
	const calculateEmptyGrids = (year : number, month : number) => {
		//计算每个月时要清零
		state.days = [];
		const firstDayOfWeek = getFirstDayOfWeek(year, month);
		if (firstDayOfWeek > 0) {
			for (let i = 0; i < firstDayOfWeek; i++) {
				var obj = {
					date: null,
					isSign: false
				}
				state.days.push(obj);
			}
		}
	}
	// 绘制当月天数占的格子，并把它放到days数组中
	const calculateDays = (year : number, month : number) => {
		const thisMonthDays = getThisMonthDays(year, month);
		for (let i = 1; i <= thisMonthDays; i++) {
			var obj = {
				date: i,
				isSign: false
			}
			state.days.push(obj);
		}
	}
	//匹配判断当月与当月哪些日子签到打卡
	const onJudgeSign = () => {
		var signs = state.SignUp;
		var daysArr = state.days;
		for (var i = 0; i < signs.length; i++) {
			var current = new Date(signs[i].replace(/-/g, "/"));
			var year = current.getFullYear();
			var month = current.getMonth() + 1;
			var day = current.getDate();
			day = parseInt(String(day));
			for (var j = 0; j < daysArr.length; j++) {
				//年月日相同则打卡成功
				if (year == state.cur_year && month == state.cur_month && daysArr[j].date == day) {
					daysArr[j].isSign = true;
				}
			}
		}
		state.days = daysArr;
	}

	/** 切换控制年月，上一个月，下一个月 */
	const handleCalendar = (type : number) => {
		const cur_year = parseInt(String(state.cur_year));
		const cur_month = parseInt(String(state.cur_month));
		let newMonth : any = '';
		let newYear = cur_year;
		if (type === 0) { //上个月
			newMonth = cur_month - 1;
			if (newMonth < 1) {
				newYear = cur_year - 1;
				newMonth = 12;
			}
		} else {
			newMonth = cur_month + 1;
			if (newMonth > 12) {
				newYear = cur_year + 1;
				newMonth = 1;
			}
		}
		calculateEmptyGrids(newYear, newMonth);
		calculateDays(newYear, newMonth);

		state.cur_year = newYear;
		state.cur_month = newMonth;

		state.SignUp = []; //先清空

		getUserCheckByMonth(state.cur_year, state.cur_month);

	}

	/** 签到 */
	const clickSignUp = async (date : any, type : number) => {
		//如果不需要补签功能直接在这阻止不执行后面的代码就行。
		if (type == 0) {
			return false;
		}
		let postDate = state.cur_year + "-" + state.cur_month + "-" + date;
		const userCheckIn : Response<any> = await queryUserCheckIn({
			date: postDate,
		})
		if (userCheckIn?.status) {
			handleShowToast('签到成功', 'success');
			state.dataSource.push(state.cur_year + "-" + state.cur_month + "-" + date);
			if (userCheckIn.data) {
				state.sumCount = userCheckIn.data.cumulativeCheckInCount;
			}
			onJudgeSign();
		} else {
			handleShowToast(userCheckIn.msg)
		}
	}
</script>
<style lang="scss" scoped>
	@import './checkIn.scss';
</style>